import { groupRequired } from '../../middleware/jwt';
import { logger } from '../../middleware/logger';
import { FlowDao } from '../../dao/flow';
import { LinRouter } from 'lin-mizar';
import { AddFlowValidator, DeleteFlowValidator, EditFlowValidator } from '../../validators/flow';
import { FlowService } from '../../service/flow';

const flowApi = new LinRouter({
  prefix: '/v1/flow'
});
// 插入flow数据
flowApi.linPost(
  'addFlow',
  '/',
  {
    permission: '新增最新期刊',
    module: '最新期刊管理',
    mount: true
  },
  groupRequired,
  logger('{user.username}新增最新期刊'),
  async ctx => {
    const cf = await new AddFlowValidator().validate(ctx);
    await FlowDao.addFlow(cf);
    ctx.success({
      mag: '数据添加成功'
    });
  }
);
// 查询flow数据
flowApi.get('/', async ctx => {
  // 1. 查flow表数据
  // 2. 依据flow表中的art_id,type字段去查询相应期刊的数据
  // 3. 格式化数据
  // 4. 返回结果
  const flowList = await FlowService.getFlowList();
  ctx.json(flowList);
});
// 修改flow数据
flowApi.linPost(
  'editFlow',
  '/:id',
  {
    permission: '编辑最新期刊',
    module: '最新期刊',
    mount: true
  },
  groupRequired,
  logger('{user.username}编辑了最新期刊'),
  async ctx => {
    const ef = await new EditFlowValidator().validate(ctx);
    const id = ef.get('path.id');
    const index = ef.get('body.index');
    const type = ef.get('body.type');
    const art_id = ef.get('body.art_id');
    const status = ef.get('body.status');
    await FlowDao.editFlow(id, index, type, art_id, status);
    ctx.success({
      msg: '最新期刊修改成功 '
    });
  }
);
flowApi.linDelete(
  'deleteFlow',
  '/:id',
  {
    permission: '删除最新期刊',
    module: '最新期刊管理',
    mount: true
  },
  groupRequired,
  logger('{user.username}删除了最新期刊'),
  async ctx => {
    const df = await new DeleteFlowValidator().validate(ctx);
    await FlowDao.deleteFlow(df.get('path.id'));
    ctx.success({
      msg: '最新期刊删除成功'
    });
  }
);
module.exports = { flowApi };